package leetcode;

public class LeetCode2 {

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }


    public ListNode addTwoNumbers1(ListNode l1, ListNode l2) {
        boolean next = false;
        ListNode preL1 = null;
        ListNode result = l1;
        while (l2 != null) {
            if (l1 == null) {
                int i = +l2.val + (next ? 1 : 0);
                next = false;
                if (i > 10) {
                    i -= 10;
                    next = true;
                }
                ListNode node = new ListNode(i);
                preL1.next = node;
                l1 = node;
                preL1 = preL1.next;
                l2 = l2.next;
            } else {
                int i = l1.val + l2.val + (next ? 1 : 0);
                next = false;
                if (i >= 10) {
                    i -= 10;
                    next = true;
                }
                l1.val = i;
                preL1 = l1;
                l1 = l1.next;
                l2 = l2.next;
            }
        }
        if (next)
            l1.next = new ListNode(1);
        return result;
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = new ListNode(0), node = result;
        boolean next = false;
        int tmp;
        while (l1 != null || l2 != null) {
            tmp = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + (next ? 1 : 0);
            if (tmp >= 10) {
                tmp -= 10;
                next = true;
            } else {
                next = false;
            }
            node.next = new ListNode(tmp);
            node = node.next;
            l1 = l1 != null ? l1.next : null;
            l2 = l2 != null ? l2.next : null;
        }
        if (next)
            node.next = new ListNode(1);
        return result.next;
    }
}
